import tkinter as tk
import requests
from tkinter import messagebox
import parsel

class DoubanSearchApp:
    def __init__(self, root):
        self.root = root
        self.root.title("豆瓣搜索")

        label = tk.Label(root, text="请输入您要搜索的内容", anchor='w')
        label.pack(fill='x', pady=5)

        self.entry = tk.Entry(root, width=50)
        self.entry.pack(pady=20)

        search_button = tk.Button(root, text="搜索", command=self.search_douban)
        search_button.pack(pady=10)

    def search_douban(self):
        query = self.entry.get()
        if not query:
            messagebox.showwarning("输入错误", "请输入搜索内容")
            return

        url = f"https://search.douban.com/movie/subject_search?search_text={query}"
        try:
            headers = self.get_headers()
            response = requests.get(url, headers=headers)

            selector = parsel.Selector(response.text)
            titles = selector.css(".title::text").getall()
            links = selector.css(".title").xpath('@href').getall()
            scores = selector.css(".rating_num::text").getall()
            introductions = selector.css(".inq::text").getall()

            for i in range(len(titles)):
                print(f"标题：{titles[i]}")
                print(f"链接：{links[i]}")
                print(f"评分：{scores[i]}")
                print(f"简介：{introductions[i]}")
                print("\n")
        except requests.exceptions.RequestException as e:
            messagebox.showerror("错误", str(e))

    def get_headers(self):
        return {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
                          " (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
        }

if __name__ == "__main__":
    root = tk.Tk()
    app = DoubanSearchApp(root)
    root.mainloop()